"""This Task use ssh to login a remote node """
import sys,os
sys.path.append(os.path.abspath('..'))
from service.PlusterLog import PlusterLog
from MVC.plstdocument import IDocument
from MVC.vb_tk import *
from tkMessageBox import *


class SSHTask(PlusterLog,IDocument):
    def __init__(self):
        PlusterLog.__init__(self)
        IDocument.__init__(self)
        self.log.info("SSH Task initalize")
        self.err=""

    def config(self,arg):
        self.ip=arg

    def set_user(self,user):
        self.user=user

    def run(self):
        cmd="xterm -e ssh "+self.user+"@"+self.ip
        self.log.debug("SSH command:%s"%cmd)
        self.log.debug("cmd is "+cmd)
        msg=os.system(cmd)
        if msg!=0:
            self.err="Error: Can not connect host"
            self.log.error(self.err)
            return -1



class SSHAdapter:
    def __init__(self,doc):
        self.doc=doc
    def HandleRequest(self,user):
        print "ssh adapter userName is %s"%user
        self.doc.set_user(user)
        return self.doc.run()


class SSHView(VBtk):
    def __init__(self,ctl):
        self.ctl=ctl

    def show(self,root):
        self.toplevel=Toplevel(root)
        self.LoadFrm("SSH.frm",self.toplevel)
        self.toplevel

    def WECB_Command1_Click(self,event):
        err=self.ctl.HandleRequest(self.master.Form1.Text1.text.get("1.0","1.end"))
        if err==-1:
            showerror("SSH Error","Error: Can not connect host,check SSH Daemon")
    def Update(self,doc):
        pass


if __name__=="__main__":
    import logging
    logging.basicConfig()
    logging.getLogger().setLevel(logging.DEBUG)
    #ssh=SSHTask("root","127.0.0.1")
    ssh.Login()

